#!/usr/bin/env python

from liwe.module import LiweModule

class PageManager ( LiweModule ):
	def __init__ ( self, liwe ):
		super ( PageManager, self ).__init__ ( liwe, "page_manager" )

		self.dbm = self.liwe.dbm

	#=================================================
	# OVERRIDDABLE METHODS
	#=================================================
	def text_manip ( self, text ):
		"""
		Redefine this method to modify ``text`` *BEFORE* it is inserted
		inside the database.

		The method should return the ``text`` itself.
		"""
		return text

	#=================================================
	# PUBLIC METHODS
	#=================================================
	def add ( self, text, id_page = 0, page_name = '', module = '', perms = 644, internal = 0 ):
		uid = self.liwe.pyhp.session.data.get ( "uid", 0 )
		gid = self.liwe.pyhp.session.data.get ( "gid", 0 )

		text = self.text_manip ( text )

		dct = { "txt": text,
			"perms": perms,
			"page_name": page_name
		}

		id_site = self.site_id

		if not id_page:
			dct [ 'created' ] = "*NOW()"
			dct [ 'uid' ] = uid
			dct [ 'gid' ] = gid
			dct [ 'id_site' ] = id_site
			dct [ 'module' ] = module
			dct [ 'internal' ] = internal

			self.dbm.insert ( "page", dct )
			id_page = self.dbm.insert_id ()
		else:
			self.dbm.update ( "page", dct, "id_page = %s" % id_page )

		return id_page

	def delete ( self, id_page ):
		self.dbm.delete ( "page", "id_page = '%s'" % id_page )

	def get ( self, id_page, page_name = '' ):
		conds = "id_page = '%s'" % id_page
		if page_name:
			conds = "page_name = '%s'" % page_name

		vals =  self.dbm.single_row ( "page", [ "id_page", "page_name", "txt", "uid", "gid", "created" ], conds, debug = self.debug () ) 
		return vals

	def search ( self, testo, module, fields = None ):
		id_site = self.site_id
		conds = [ "id_site = %s" % id_site ]
		conds.append ( "internal = 0" )
		if testo:
			conds.append ( "txt LIKE '%%%s%%'" % testo )

		if module:
			conds.append ( "module = '%s'" % module )

		conds = " AND ".join ( conds )
	
		if not fields:
			fields = [ "id_page", "page_name", "txt", "module", "id_site" ]

		res =  self.dbm.all_rows ( "page", fields, conds = conds, extras = "ORDER BY id_page" )
		if not res: return []

		return res

	def list ( self ):
		conds = "internal = 0"
		res = self.dbm.all_rows ( "page", [ "id_page", "page_name", "txt", "module", "id_site" ], conds = conds , extras = "ORDER BY id_page" )
		if not res: return []

		return res
